package org.example.service;

import org.example.dao.BankCardDao;
import org.example.dao.FlowDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class TransferService {
    @Autowired
    private BankCardDao cardDao;
    @Autowired
    private FlowDao flowDao;

    /* 1. 正常转账：A → B 1000 元 */
    @Transactional(rollbackFor = Exception.class)
    public void transferA2B(long aCardId, long bCardId, BigDecimal amt){
        // A 支出
        cardDao.updateBalance(aCardId, amt.negate());
        flowDao.insertFlow(aCardId, bCardId, 1, amt);

        // B 收入
        cardDao.updateBalance(bCardId, amt);
        flowDao.insertFlow(aCardId, bCardId, 0, amt);
    }

    /* 2. 模拟异常转账：B → A，中途抛异常 */
    @Transactional(rollbackFor = Exception.class)
    public void transferB2AWithError(long bCardId, long aCardId, BigDecimal amt){
        // B 支出
        cardDao.updateBalance(bCardId, amt.negate());
        flowDao.insertFlow(bCardId, aCardId, 1, amt);

        // 模拟异常
        int x = 1 / 0;

        // A 收入（不会执行）
        cardDao.updateBalance(aCardId, amt);
        flowDao.insertFlow(bCardId, aCardId, 0, amt);
    }
}